#!/bin/sh

# Slackware script to package the libretro cores for SBo.
# The libretro git SlackBuilds are required for use.

# Pacakges all of the libretro cores by default.
# ./retropkg foo will package the foo core.

# Copyright 2016-2018 orbea
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

REMOTE=${REMOTE:-ovhtoo:~/web/stuff/slackbuilds/src/libretro}
SRCURL=${SRCURL:-http://ks392457.kimsufi.com/orbea/stuff/slackbuilds/src/libretro}
GITURL=${GITURL:-https://raw.githubusercontent.com/libretro/libretro-super/master/dist/info}
GITDIR=${GITDIR:-/media/gittings/orbea/SlackBuilds-git}
OUTPUT=${OUTPUT:-/media/data/home/backup/SBo/libretro/gittings}
SLKBLD=${SLKBLD:-/media/gittings/orbea/SlackBuilds}
SRCDIR=${SRCDIR:-/media/data/home/src/SBo}
SUBMIT=${SUBMIT:-/tmp/SBo_submit}
SRC=${SRC:-/media/data/home/backup/SBo/libretro/src}

set -e

mkdir -p "$OUTPUT" "$SUBMIT" "$SRC"
trap 'rm -rf -- $OUTPUT' EXIT

core_info () {
  PRGNAM="$(sed -n 's/^PRGNAM=//p' "$core.info" | tr -d '\"')"
  BRANCH="$(sed -n 's/^BRANCH=//p' "$core.info" | tr -d '\"')"
  DOWNLOAD="$(sed -n 's/^DOWNLOAD=//p' "$core.info" | tr -d '\"' | sed 's/\s.*$//')"
  eval "LIBNAM=$(sed -n 's/^LIBNAM=//p' "$core.SlackBuild")"
}

core_libretro () {
  case "$PKGDIR" in
    libretro )
      COREDIR="$(basename "$(dirname "$(dirname "$(dirname "$core")")")")/libretro"
    ;;
    * )
      COREDIR="$PKGDIR"
    ;;
  esac
}

core_dir () {
  PKGDIR="$(basename "$(dirname "$(dirname "$core")")")"
  core_libretro
  NEWDIR=$GITDIR/$COREDIR
  SBODIR=$SLKBLD/$COREDIR
  SBO=$SRCDIR/$COREDIR
}

core_version () {
  COMMIT="$(git rev-parse --short HEAD)"
  DATE="$(git show -s --format=%ad --date=format:%Y.%m.%d)"
  VERSION="${DATE}_$COMMIT"
}

core_submodule () {
  if git config --file .gitmodules --name-only --get-regexp path >/dev/null 2>&1; then
    git submodule update --init
  fi
}

core_libnam () {
  case "$PRGNAM" in
    beetle-psx-libretro )
      PROFILE='psx psx_hw'
      CORECMD='$(printf %s $LIBNAM | sed "s/psx/$profile/")'
    ;;
    bsnes-libretro|bsnes-mercury )
      PROFILE='accuracy balanced performance'
      CORECMD='${LIBNAM}_${profile}_libretro'
    ;;
    libretro-samples )
      PROFILE="testaudio_callback testaudio_no_callback \\
        testaudio_playback_wav button_test cruzes testgl_compute_shaders \\
        testgl_ff testgl freebasic pascal_pong testsw testsw_vram test \\
        advanced_tests testvulkan_async_compute testvulkan"
      CORECMD='${profile}_libretro'
    ;;
    mame2014-libretro )
      PROFILE='mame mess ume'
      CORECMD='${profile}2014_libretro'
    ;;
    parallel-n64 )
      PROFILE='parallel_n64 parallel_n64_debug'
      CORECMD='${profile}_libretro'
    ;;
    * )
      PROFILE="$LIBNAM"
      CORECMD='$profile'
    ;;
  esac
}

core_curl () {
  eval "set -- $PROFILE"
  for profile do
    eval "CORENAM=$CORECMD"
    curl -O "$GITURL/$CORENAM.info"
  done
}

core_clone () {
  git clone --depth=1 -b "$BRANCH" "$DOWNLOAD" "$OUTPUT/$PRGNAM"
  cd -- "$OUTPUT/$PRGNAM"
  core_version
  core_submodule
  find . -name '.git*' | xargs rm -rf
  core_libnam
  core_curl
  cd - >/dev/null 2>&1
  ( cd "$OUTPUT"; rename "$PRGNAM" "$PRGNAM-$VERSION" "$PRGNAM" )
}

core_clean () {
  for src in $SRC/$PRGNAM-*.tar.xz; do
    if [ -f "$src" ]; then
      mv -- "$src" "$SRC/.old"
      rm -f -- "$SBO/$PRGNAM/$PRGNAM-*.tar.xz"
      rm -f -- "$SUBMIT/$PRGNAM-*.tar.gz"
    fi
  done
}

core_var () {
  SED_INFO="s|BRANCH=.*|VERSION=\"$VERSION\"|;s|DOWNLOAD=.*|DOWNLOAD=\"$SRCURL/$PRGNAM-$VERSION.tar.xz\"|"
  SED_MAINTAINER="s|MAINTAINER=.*|MAINTAINER=\"$MAINTAINER\"|"
  SED_BRANCH="s|BRANCH=.*|VERSION=\${VERSION:-$VERSION}|;s|# Copyright.*|# Copyright $(date +"%Y") $MAINTAINER $LOCATION|"
  SED_GIT='s|git clone.*|tar xvf $CWD/$PRGNAM-$VERSION.tar.xz|;s|_git|_SBo|'
  SED_MAKE='s|$PRGNAM-${VERSION}_$BRANCH-$ARCH|$PRGNAM-$VERSION-$ARCH|'
  SED_PRGNAM='s|rm -rf $PRGNAM|rm -rf $PRGNAM-$VERSION|;s|cd $PRGNAM|cd $PRGNAM-$VERSION|'
  SED_BUILD="s|^VERSION=.*|VERSION=\${VERSION:-$VERSION}|"
  SED_VERSION="s|VERSION=.*|VERSION=\"$VERSION\"|"
  SED_GITVERS='/DEBUG=$DEBUG/s/$/ GIT_VERSION="\${VERSION#*_}"/'
  SED_LIBNAM='/install -Dm0644 $LIBNAM.so/a install -Dm0644 $LIBNAM.info $PKG/usr/lib${LIBDIRSUFFIX}/libretro/info/$LIBNAM.info'
  MD5SUM=$(md5sum "$SRC/$PRGNAM-$VERSION.tar.xz" | cut -d ' ' -f 1)
}

core_sed () {
  sed -e "$SED_INFO;$SED_MAINTAINER" \
      -e '/DOWNLOAD=.*/a MD5SUM=""\nDOWNLOAD_x86_64=""\nMD5SUM_x86_64=""' \
      -i "$SBO/$PRGNAM/$PRGNAM.info"
  sed -e "$SED_BRANCH;$SED_GIT;$SED_MAKE;$SED_PRGNAM" \
      -e '/SRCNAM/d;/COMMIT/d;/DATE/d;/HEAD/d' \
      -e '/install -Dm0644 $LIBNAM.so/{n;N;N;N;d}' \
      -e "$SED_GITVERS;$SED_LIBNAM" \
      -i "$SBO/$PRGNAM/$PRGNAM.SlackBuild"
}

core_convert () {
  if [ ! -d "$SBO/$PRGNAM" ]; then
    cp -a "$NEWDIR/$PRGNAM" "$SBO"
    core_sed
    chmod 0755 "$SBO/$PRGNAM/$PRGNAM.SlackBuild"
  fi
}

core_new () {
  if [ ! -d "$SBODIR/$PRGNAM" ]; then
    core_convert
    mkdir -p "$SBODIR/$PRGNAM"
    DIFF="-uN"
    MSG="$(awk -F "[()]" '{ for (i=2; i<NF; i+=2) print $i }' \
         "$SBO/$PRGNAM/slack-desc" | head -1)"
    GIT="$COREDIR/$PRGNAM: Added ($MSG)."
  else
    DIFF="-u"
    GIT="$COREDIR/$PRGNAM: Upgraded to $VERSION."
  fi
}

core_hack () {
  # hack for bluemsx
  if grep -q '\\$' "$SBO/$PRGNAM/$PRGNAM.info"; then
    SED_HACK="s|$PRGNAM-.*.tar.xz.*|$PRGNAM-$VERSION.tar.xz \\\\|;s|MD5SUM=.*|MD5SUM=\"$MD5SUM \\\\|"
  # hack for x86_64 only scripts
  elif grep -q UNSUPPORTED "$SBO/$PRGNAM/$PRGNAM.info"; then
    SED_HACK="s|$PRGNAM-.*.tar.xz\"|$PRGNAM-$VERSION.tar.xz\"|;s|MD5SUM_x86_64=.*|MD5SUM_x86_64=\"$MD5SUM\"|"
  else
    SED_HACK="s|$PRGNAM-.*.tar.xz\"|$PRGNAM-$VERSION.tar.xz\"|;s|MD5SUM=.*|MD5SUM=\"$MD5SUM\"|"
  fi
}

core_newline () {
  for file in $(find "$SBO/$PRGNAM" -type f -exec grep -Iq . {} \; -and -print); do
    if [ -s "$file" ] && [ "$(tail -c1 "$file"; echo x)" != $'\nx' ]; then
      sed -i '$a\' "$file"
    fi
  done
}

core_date () {
  copyright="$(grep '# Copyright' "$SBO/$PRGNAM/$PRGNAM.SlackBuild")"
  year="$(date +'%Y')"
  prev="$((year-1))"
  case "$copyright" in
    *$year* )
      return
    ;;
    *-$prev* )
      new_copy="$(printf %s "$copyright" | sed "s/-${prev}/-${year}/")"
    ;;
    *$prev* )
      new_copy="$(printf %s "$copyright" | sed "s/${prev}/${prev}-${year}/")"
    ;;
  esac
  sed -i "s|$copyright|$new_copy|" "$SBO/$PRGNAM/$PRGNAM.SlackBuild"
}

core_edit () {
  core_var
  core_new
  core_hack
  core_newline
  core_date
  sed -i "$SED_BUILD" "$SBO/$PRGNAM/$PRGNAM.SlackBuild"
  sed -i "$SED_VERSION;$SED_HACK" "$SBO/$PRGNAM/$PRGNAM.info"
}

core_commit () {
  ( cd -- "$SBO"
    diff $DIFF "$SBODIR/$PRGNAM" "$PRGNAM" | \
      tee "$OUTPUT/$PRGNAM.patch" >/dev/null 2>&1
  )
  ( cd -- "$SBODIR/$PRGNAM"
    patch -p1 -i "$OUTPUT/$PRGNAM.patch"
    git add .
    git commit -m "$GIT"
  )
}

core_submit () {
  cp -a "$SBODIR/$PRGNAM" "$SUBMIT"
  ( cd "$SUBMIT"
    chmod 755 "$PRGNAM/$PRGNAM.SlackBuild"
    tar cvzf "$PRGNAM.tar.gz" "$PRGNAM" >/dev/null 2>&1
    rm -rf "$PRGNAM"
    printf %s\\n "Uploading $PRGNAM-$VERSION.tar.xz now..."
    scp "$SRC/$PRGNAM-$VERSION.tar.xz" "$REMOTE"
  )
}

core_pkg () {
  if [ ! -f "$SRC/$PRGNAM-$VERSION.tar.xz" ]; then
    core_clean
    printf %s\\n "Compressing $PRGNAM-$VERSION.tar.xz now..."
    ( cd "$OUTPUT"
      tar cf - "$PRGNAM-$VERSION" | xz -c9 - > "$SRC/$PRGNAM-$VERSION.tar.xz"
    )
    core_edit
    cp -a "$SRC/$PRGNAM-$VERSION.tar.xz" "$SBO/$PRGNAM"
    core_commit
    core_submit
  fi
}

core_name () {
  if [ -z "$1" ]; then
    CORE="*"
    INFO="games/libretro"
  else
    CORE="$1"
    INFO=""
  fi
}

core_all () {
  for core in $(find "$GITDIR/$INFO" -type f -name "$CORE.info" | rev | \
      cut -f2 -d"." | rev | sort); do
    core_info
    core_dir
    core_clone
    core_pkg
  done
}

core_notify () {
  if [ -x /usr/bin/notify-send ]; then
    notify-send 'Libertro cores are ready to send to SBo'
  else
    echo 'Liberetro cores are ready to send to SBo.'
  fi
}

core_name "$1"
core_all
core_notify
